﻿/*==============================================================================
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc.
All Rights Reserved.
==============================================================================*/

using System;
using UnityEngine;
using System.Collections;
using System.Text.RegularExpressions;

/// <summary>
/// This MonoBehaviour implements the Cloud Reco Event handling for this sample.
/// It registers itself at the CloudRecoBehaviour and is notified of new search results as well as error messages
/// The current state is visualized and new results are enabled using the TargetFinder API.
/// </summary>
public class CloudRecoEventHandler : MonoBehaviour, ICloudRecoEventHandler
{
    #region PRIVATE_MEMBER_VARIABLES

    // ImageTracker reference to avoid lookups
    private ImageTracker mImageTracker;
    private string mTargetMetadata = "";
	ArrayList list=new ArrayList();// Guarda la cadena separa de metadata package
    private Empresa unaEmpresa=new Empresa();
	
    // the parent gameobject of the referenced ImageTargetTemplate - reused for all target search results
    private GameObject mParentOfImageTargetTemplate;

    #endregion // PRIVATE_MEMBER_VARIABLES



    #region EXPOSED_PUBLIC_VARIABLES

    /// <summary>
    /// can be set in the Unity inspector to reference a ImageTargetBehaviour that is used for augmentations of new cloud reco results.
    /// </summary>
    public ImageTargetBehaviour ImageTargetTemplate;

    #endregion

    #region ICloudRecoEventHandler_IMPLEMENTATION

    /// <summary>
    /// called when TargetFinder has been initialized successfully
    /// </summary>
    public void OnInitialized()
    {
        // get a reference to the Image Tracker, remember it
        mImageTracker = TrackerManager.Instance.GetTracker<ImageTracker>();
    }

    /// <summary>
    /// visualize initialization errors
    /// </summary>
    public void OnInitError(TargetFinder.InitState initError)
    {
        switch (initError)
        {
            case TargetFinder.InitState.INIT_ERROR_NO_NETWORK_CONNECTION:
                ErrorMsg.New("Red No Disponible", "Por favor, compruebe su conexión a Internet y vuelva a intentarlo.", RestartApplication);
                break;
            case TargetFinder.InitState.INIT_ERROR_SERVICE_NOT_AVAILABLE:
                ErrorMsg.New("Servicio No Disponible", "No se pudo inicializar la aplicación porque el servicio no está disponible.");
                break;
        }
    }
    
    /// <summary>
    /// visualize update errors
    /// </summary>
    public void OnUpdateError(TargetFinder.UpdateState updateError)
    {
        switch (updateError)
        {
            case TargetFinder.UpdateState.UPDATE_ERROR_AUTHORIZATION_FAILED:
			    ErrorMsg.New("Error de Autorización","Las claves de acceso al servicio de reconocimiento de la nube es incorrectos o han expirado.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_NO_NETWORK_CONNECTION:
			    ErrorMsg.New("Red No Disponible","Por favor, compruebe su conexión a Internet y vuelva a intentarlo.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_PROJECT_SUSPENDED:

		     	ErrorMsg.New("Error de Autorización","El servicio de reconocimiento de la nube ha sido suspendido.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_REQUEST_TIMEOUT:

			      ErrorMsg.New("Solicitud de tiempo de espera","La solicitud de red ha caducado, por favor revise su conexión a Internet y vuelva a intentarlo.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_SERVICE_NOT_AVAILABLE:
			    ErrorMsg.New("Servicio No Disponible","El servicio no está disponible, por favor intente de nuevo más tarde.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE:
                ErrorMsg.New("Error de Sincronizacion del Reloj","Por favor, actualice la fecha y la hora y vuelva a intentarlo.");
                break;
            case TargetFinder.UpdateState.UPDATE_ERROR_UPDATE_SDK:
                ErrorMsg.New("Versión no compatible","La aplicación utiliza una versión no compatible de Vuforia.");
                break;
        }
    }

    /// <summary>
    /// when we start scanning, unregister Trackable from the ImageTargetTemplate, then delete all trackables
    /// </summary>
    public void OnStateChanged(bool scanning)
    {
        if (scanning)
        {
            // clear all known trackables
            mImageTracker.TargetFinder.ClearTrackables(false);
        }
    }
    
    /// <summary>
    /// Handles new search results
    /// </summary>
    /// <param name="targetSearchResult"></param>
    public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
    {
        // This code demonstrates how to reuse an ImageTargetBehaviour for new search results and modifying it according to the metadata
        // Depending on your application, it can make more sense to duplicate the ImageTargetBehaviour using Instantiate(), 
        // or to create a new ImageTargetBehaviour for each new result

        // Vuforia will return a new object with the right script automatically if you use
        // TargetFinder.EnableTracking(TargetSearchResult result, string gameObjectName)
        
        //Check if the metadata isn't null
		mTargetMetadata = targetSearchResult.MetaData;
		list.AddRange(Regex.Split(mTargetMetadata,"->"));
		if(targetSearchResult.MetaData != null)
        {
			unaEmpresa=this.CrearEmpresa(list);
		}
        if(targetSearchResult.MetaData == null)
        {
            return;
        }

        // First clear all trackables
        mImageTracker.TargetFinder.ClearTrackables(false);

        // enable the new result with the same ImageTargetBehaviour:
        ImageTargetBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking(targetSearchResult, mParentOfImageTargetTemplate) as ImageTargetBehaviour;
        
        //if extended tracking was enabled from the menu, we need to start the extendedtracking on the newly found trackble.
        if(CloudRecognitionUIEventHandler.ExtendedTrackingIsEnabled)
        {
            imageTargetBehaviour.ImageTarget.StartExtendedTracking();
        }
    }

    #endregion // ICloudRecoEventHandler_IMPLEMENTATION



    #region UNTIY_MONOBEHAVIOUR_METHODS

    /// <summary>
    /// register for events at the CloudRecoBehaviour
    /// </summary>
    void Start()
    {
       
		// look up the gameobject containing the ImageTargetTemplate:
        mParentOfImageTargetTemplate = ImageTargetTemplate.gameObject;

        // intialize the ErrorMsg class
        ErrorMsg.Init();

        // register this event handler at the cloud reco behaviour
        CloudRecoBehaviour cloudRecoBehaviour = GetComponent<CloudRecoBehaviour>();
        if (cloudRecoBehaviour)
        {
            cloudRecoBehaviour.RegisterEventHandler(this);
        }
    }

    /// <summary>
    /// draw the sample GUI and error messages
    /// </summary>
    void OnGUI()
    {

//		    GUI.Box (new Rect(0,0,200,50), "Metadata: " + list.Count+"");
//		    if(list.Count>0){
//		    GUI.Box (new Rect(0,100,200,50), "Metadata: " + list[0]+"");
//			GUI.Box (new Rect(0,200,200,50), "Metadata: " + list[1]+"");
//			GUI.Box (new Rect(0,300,200,50), "Metadata: " + list[2]+"");
//			GUI.Box (new Rect(0,400,200,50), "Metadata: " + list[3]+"");
//			GUI.Box (new Rect(0,500,200,50), "Metadata: " + list[4]+"");
//			GUI.Box (new Rect(0,600,200,50), "Metadata: " + list[6]+"");
//			GUI.Box (new Rect(0,700,200,50), "Metadata: " + list[7]+"");
//		    }
	

        ErrorMsg.Draw();
    }

    #endregion UNTIY_MONOBEHAVIOUR_METHODS

    #region PRIVATE_METHODS
    
    // callback for network-not-available error message
    private void RestartApplication()
    {
        Application.LoadLevel("Vuforia-2-LoadingScene");
    }
	public ArrayList getList(){
		return list;
	}
	public Empresa getEmpresa(){
		return unaEmpresa;
	}
	public void limpiarLista(){
		list.Clear();
	}
	public Empresa CrearEmpresa(ArrayList list){
		Empresa unaEmpresa=new Empresa(list[0]+"",list[1]+"",list[2]+"",list[3]+"",list[4]+"",list[5]+"");
		return unaEmpresa;
	}
    #endregion PRIVATE_METHODS
}
